package cn.lili.common.processor;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.ReflectUtil;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Configuration
public class JacksonConfigurer {

    /**
     * 序列化 null(空) 值
     */
//    @Bean
//    @Primary
//    public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
//        ObjectMapper objectMapper = builder.createXmlMapper(false).build();
//        objectMapper.getSerializerProvider().setNullValueSerializer(new NullValueSerializer());
//        return objectMapper;
//    }
}


/**
 * 空值序列化
 */
class NullValueSerializer extends JsonSerializer<Object> {

    @Override
    public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        String fieldName = gen.getOutputContext().getCurrentName();
        //反射获取空值字段
        Field field = ReflectUtil.getField(gen.getCurrentValue().getClass(), fieldName);
        if (ObjectUtil.isNotNull(field)) {
            // 数字类型Integer、Double、Long等返回null
            if (Number.class.isAssignableFrom(field.getType())) {
                gen.writeString("");
                return;
            }
            //String类型返回""
            if (Objects.equals(field.getType(), String.class)) {
                gen.writeString("");
                return;
            }
            //String类型返回""
            if (field.getType().equals(Date.class) || field.getType().isInstance(Date.class)) {
                gen.writeString("");
                return;
            }
            //List类型返回[]
            if (Objects.equals(field.getType(), List.class)) {
                gen.writeStartArray();
                gen.writeEndArray();
                return;
            }
            //其他Object默认返回{}
            gen.writeStartObject();
            gen.writeEndObject();
        }
    }
}
